package com.levy.utils.security;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.levy.utils.provider.impl.SessionParamProvider;

public class SecurityFilter implements Filter{

	private Logger logger = Logger.getLogger(SecurityFilter.class);
	
	public FilterConfig config;

    public static boolean isContains(String container, String[] regx) {
        boolean result = false;
        for (int i = 0; i < regx.length; i++) {
            if (container.indexOf(regx[i]) != -1) {
                return true;
            }
        }
        return result;
    }
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		config = filterConfig;
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest rq = (HttpServletRequest)request;
		HttpServletResponse rs = (HttpServletResponse)response;
		String path = rq.getContextPath();
		System.out.println(rq.getRequestURI());
		String logonStrings = config.getInitParameter("logonStrings"); // 登录登陆页面
		String includeStrings = config.getInitParameter("includeStrings"); // 过滤资源后缀参数
		String redirectPath = path+ config.getInitParameter("redirectPath");// 没有登陆转向页面

		String[] logonList = logonStrings.split(";");
	    String[] includeList = includeStrings.split(";");
		if (!this.isContains(rq.getRequestURI(), includeList)) {// 只对指定过滤参数后缀进行过滤
            chain.doFilter(request, response);
            return;
        }
		if (this.isContains(rq.getRequestURI(), logonList)) {// 对登录页面不进行过滤
	            chain.doFilter(request, response);
	            return;
	    }
		//如果已经登录
		SessionParamProvider sp = new SessionParamProvider(rq);
		if(sp != null && sp.getParameter("session_userid") != null){
			chain.doFilter(request, response);
		}else{
			rs.sendRedirect(path+"/page/index.html");
		}
		
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
